package com.uinnova.development.common;


public class HashMap<K,V> implements Map<K,V>{

    private Entry<K,V> table[] = null;

    int size = 0;

    public HashMap(){
        table = new Entry[16];
    }
    @Override
    public V put(K k, V v) {
        int index = hash(k);
        Entry<K,V> entry = table[index];
        if(null == entry){
            //数组存储
           table[index] = new Entry(k,v,index,null);
           size++;
        }else{
            //链表存储
            table[index] = new Entry(k,v,index,entry);
        }

        return table[index].getValue();
    }

    /**
     * 传入键取模
     * @param k
     * @return
     */
    private int hash(K k){
        int index = k.hashCode()%16;
        //可能会出现取模负值的情况
        return index >= 0 ? index : -index;
    }

    @Override
    public V get(K k) {
        if(size == 0){
            return null;
        }
        int index = hash(k);
        Entry<K,V> entry = findValue(k,table[index]);
        return entry == null ? null : entry.getValue();
    }

    @Override
    public int size() {
        return 0;
    }

    /**
     * 查数组或者链表上的数据
     * @param k
     * @param entry
     * @return
     */
    private Entry<K,V> findValue(K k,Entry<K,V> entry){
        if(k.equals(entry.getKey()) || k == entry.getKey()){
            return entry;
        }else {
            if(entry.next != null){
                return findValue(k,entry.next);
            }
        }
        return null;
    }

    class Entry<K,V> implements Map.Entry<K,V>{
        K k;V v;int hash;Entry<K,V> next;

        public Entry(K k, V v, int hash, Entry<K, V> next) {
            this.k = k;
            this.v = v;
            this.hash = hash;
            this.next = next;
        }

        public Entry(K k, V v, int index, Object o) {
        }

        @Override
        public K getKey() {
            return k;
        }

        @Override
        public V getValue() {
            return v;
        }
    }
}
